# !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
功能描述
----------------------------------------------------
@Project :   xinhou-openai-framework  
@File    :   PublicController.py    
@Contact :   sp_hrz@qq.com

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2023/4/4 11:27   shenpeng   1.0         None
"""
from fastapi import APIRouter, Request, Depends
from loguru import logger
from sqlalchemy.orm import Session

from apps.admin.schema.UserSchema import ReqUserFindSchema
from common.service.UserService import UserService
from xinhou_openai_framework.core.db.DatabaseManager import DatabaseManager
from xinhou_openai_framework.core.exception.BusinessException import BusinessException
from xinhou_openai_framework.core.exception.CodeEnum import CodeEnum
from xinhou_openai_framework.core.exception.GlobalExceptionType import AuthFailed
from xinhou_openai_framework.core.reponse.R import R

api = APIRouter()


@api.post("/admin/public/login",
          tags=["admin", "public"],
          summary="登录接口",
          description="登录用户信息，并返回用户基本信息用于后续的接口请求")
async def admin_public_login(
        request: Request,
        model: ReqUserFindSchema,
        db: Session = Depends(DatabaseManager().get_session)
):
    logger.info("[admin_public_login][request]:{}".format(model.json()))
    if model.login_name is None or model.login_pwd is None:
        raise BusinessException(CodeEnum.LOGIN_ERR_PWD)
    login_user = UserService(db).login(model.login_name, model.login_pwd)
    if not login_user:
        raise AuthFailed()
    request.session.update({"login_user_dict": login_user})
    return R.SUCCESS(login_user)


@api.post("/admin/public/logout",
          tags=["admin", "public"],
          summary="登出接口",
          description="登出用户信息，注销当前session会话")
async def admin_public_logout(
        request: Request
):
    login_user = request.session.get("login_user_dict")
    if login_user:
        logger.info("[admin_public_logout][request]:{}".format(login_user))
        request.session.clear()
    return R.SUCCESS()
